package ru.geyes.screw.collections;

import ru.geyes.screw.closures.Function1;

import java.util.Map;

/**
 * @author alex
 * @date 07.04.2009
 */
public class LazyHashMap<K, T> extends HashMapX<K, T> implements LazyMap<K, T> {

    private Map<K, Function1<T, K>> builders = MapXUtils.newHashMap();

    public void putLazy(K key, Function1<T, K> valueBuilder) {
        if (super.getO(key).isDefined()) {
           this.remove(key);
        }
        builders.put(key, valueBuilder);
    }

    @Override
    public T get(Object key) {
        K kKey = (K) key;
        Option<T> value = super.getO(kKey);
        if (value.isDefined()) {
            return value.get();
        } else {
            Function1<T, K> builder = builders.get(key);
            if (builder != null) {
                T t = builder.apply(kKey);
                super.put(kKey, t);
                return t;
            }
        }
        return null;
    }

    @Override
    public boolean containsKey(Object key) {
        return super.containsKey(key) || builders.containsKey(key);
    }

    @Override
    public T remove(Object key) {
        builders.remove(key);
        return super.remove(key);
    }
}
